#!/usr/bin/env python
import os
import socket
import sys
import time

#Create Socket to Asterisk server using AMI
try:
	s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
	print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
	sys.exit(); 
print 'Socket Created'

#Asterisk server configuration
host = "localhost" # Asterisk server name or ip
port = 5038 # AMI port

try:
	remote_ip = socket.gethostbyname(host)
except socket.gaierror:
	#Could not resolve
	print "Hostname could not be resolved.Exiting"
	sys.exit()

print 'Ip address of ' + host + ' is ' + remote_ip

#Connect to remote server
s.connect ((remote_ip,port))

print 'Socket connected to ' + host + ' on ip ' + remote_ip

message = """Action: Login
Username: trungvo
Secret: abc@123

Action: originate
Channel: SIP/100
WaitTime: 60
CallerId: Yen Minh <SIP/101>
Exten: 101
Context: Outgoing
Priority: 1
Action: Logoff
"""
print message.split('\n')

try:
	#s.sendall(message)
	for sm in message.split('\n'):
		print 'Sending ', sm
		s.send(sm + '\r\n')
		if sm == "":
			data = s.recv(1024)
			print data

except socket.error:
	print "Send failed"
	sys.exit()

print 'Message send successfully!'

time.sleep(5) # This is needed to get response from AMI. Otherwise we will get the message 'Broken pipe' at asterisk CLI

#Close socket
s.close()
